package com.hugehard.endpointsearch;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;

public class UDPClient {

	public static boolean isReachable_UDP(InetAddress addr, int milliSec,
			int port) throws IOException {
		boolean bRet = true;
		byte[] sendBuf = ScanTask.STR_CLIENT_PASS_WORD.getBytes();
		DatagramSocket client = new DatagramSocket();
		DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length,
				addr, port);
		client.send(sendPacket);
		byte[] recvBuf = new byte[ScanTask.STR_SERVER_PASS_WORD.getBytes().length * 2];
		DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);

		client.setSoTimeout(milliSec);

		try {
			client.receive(recvPacket);
			String recvStr = new String(recvPacket.getData(), 0,
					recvPacket.getLength());

			bRet = recvStr.equals(ScanTask.STR_SERVER_PASS_WORD);
		} catch (SocketTimeoutException ex) {
			bRet = false;
		}

		client.close();
		return bRet;
	}
}